﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using Microsoft.Practices.ServiceLocation;

namespace Arch.Services.Infrastructure
{
    public class ServiceLocatorInstanceProvider : IInstanceProvider
    {
        #region Private Fields

        private readonly Type _serviceType;

        private static IServiceLocator _container;
        private static readonly object LockObject = new object();

        #endregion

        #region Properties

        protected static IServiceLocator Container
        {
            get
            {
                if (_container == null)
                {
                    lock (LockObject)
                    {
                        _container = ServiceLocator.Current;
                    }
                }

                return _container;
            }
        }

        #endregion

        #region Constructors

        public ServiceLocatorInstanceProvider(Type serviceType)
        {
            _serviceType = serviceType;
        }

        #endregion

        #region IInstanceProvider Members

        public object GetInstance(InstanceContext instanceContext)
        {
            return GetInstance(instanceContext, null);
        }

        public object GetInstance(InstanceContext instanceContext, Message message)
        {
            return Container.GetInstance(_serviceType);
        }

        public void ReleaseInstance(InstanceContext instanceContext, object instance) { }

        #endregion

    }
}
